`timescale 1ns/10ps

module tb_div2;
   parameter n = 32;
   parameter m = 16;
//   parameter seed = 200;  //random seed

   integer seed;
   reg clk, reset;
   reg start;
   wire [n+m-1:0] D;
   wire [n-1:0] R;
   wire err, ok;
    
   reg [n-1:0]    dividend;
   reg [n-1:0]    divisor;
   reg [n+m-1:0]  quotient;
   reg [n-1:0]    remainder;
   
   div2 UDIV(clk, reset, start, dividend, divisor, D, R, ok, err);
    
   integer i;
   
    
    //generate random dividend&divisor and calculate quotient&remainder
    function [n+n+(n+m)+(n)-1:0] gen_rand_data;
       input integer i;
       reg [n+m-1:0] dividend;
       reg [n+m-1:0] divisor;
       reg [n+m-1:0] quotient;
       reg [n+m-1:0] remainder;
       integer k;
       integer flag;
      
       begin
           k = (i/4) % 32 + 1;
           flag = 1;
           
           while(flag)
           begin
           dividend = {{$random}, {m{1'b0}}};
           divisor =  {{m{1'b0}}, {$random}};
           //quotient = {$random};
           //remainder = {$random};
           
           divisor = divisor % ( 2 << k);
           
           if(divisor == {(n+m){1'b0}})
           begin
               $display("Divisor is zero!!!");
           end else begin
               flag = 0;
           end
           
           quotient =  dividend / divisor;
           remainder = dividend % divisor;
           
           if(remainder > divisor) 
           begin
              $display("Bad remainder!!!");
              $stop;
           end
           
           if(quotient * divisor + remainder != dividend)
           begin
               $display("bad values!!!");
               $stop;
           end
           end
       
           gen_rand_data = {dividend[n+m-1:m], divisor[n-1:0], quotient, remainder[n-1:0]};
       end
    endfunction
    



   initial forever #10 clk = ~clk;

   initial
   begin
      seed = 200;
      clk = 0;
      reset = 0;
	   start = 0;

      i = $random(seed);
// 	i = $random;       
      for(i=1; i<=1000; i=i+1) 
      begin
         {dividend, divisor, quotient, remainder} = gen_rand_data(i);
         //dividend = 32'b01111101011011011111010111111010;
         //divisor  = 32'b11111001001001111001010011110010;
         //quotient = 48'b000000000000000000000000000000001000000011100000;
         //remainder= 32'b00101000110111101010110001000000;
         $display("i=%4d, dividend=32'b%b, divisor=32'b%b;\n          quotient=48'b%b, remainder=32'b%b", 
                     i, dividend, divisor, quotient, remainder);
                     
	      #20
            reset = 0;
	      #20
            reset = 1;
	         start = 1;
            
	      #1000
	         if(quotient!=D || remainder!=R) 
	         begin
	             $display("BAD RESULT!!!");
                $display("result: quotient=48'b%b, remainder=32'b%b", D, R);
                $stop;
	         end
      end
      
      $stop;
   end
endmodule
